<?php

class FeedbacksController extends Controller {

    function init() {
        $this->layout = 'contents';
    }
    
    const PAGE_SIZE = 14;

    /**
     * @var string specifies the default action to be 'index'.
     */
    public $defaultAction = 'index';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow',  // allow all users to perform 'index' and 'show' actions
                'actions' => array(),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('show', 'changeStatus'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'batchProcess'),
                'users' => array('admin'),
            ),
            array('deny',  // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Shows a particular model.
     */
    public function actionShow() {
        $feedback = $this->loadFeedback();
        $comment = FeedbackComment::model()->find("feedback_id = {$feedback->id}");
        if ($comment === null) {
            $comment = $this->newComment($feedback);
        } else {
            $comment = $this->updateComment($feedback);
        }
        
        $this->render('show', array(
            'feedback' => $feedback,
            'comment' => $comment,
        ));
    }

    // 增加回复内容
    protected function newComment($feedback) {
        $comment = new FeedbackComment();
        if (isset($_POST['FeedbackComment'])) {
            $comment->attributes = $_POST['FeedbackComment'];
            if ($feedback->addComment($comment)) {
                Feedback::model()->updateByPk($feedback->id, array('is_replied' => 1));
                Yii::app()->user->setFlash('create_comment_success', Yii::t('feedbackComment', 'create_comment_success'));
                $this->refresh();
            }
        }
        return $comment;
    }

    // 更新回复内容
    protected function updateComment($feedback) {
        $comment = FeedbackComment::model()->find("feedback_id = {$feedback->id}");
        if (isset($_POST['FeedbackComment'])) {
            $comment->attributes = $_POST['FeedbackComment'];
            if ($feedback->addComment($comment)) {
                Yii::app()->user->setFlash('update_comment_success', Yii::t('feedbackComment', 'update_comment_success'));
                $this->refresh();
            }
        }
        return $comment;
    }

    // 批量更新
    public function actionBatchProcess() {
        if (Yii::app()->request->isPostRequest) {
            $action = strtolower(trim(Yii::app()->request->getPost('action_list')));
            switch ($action) {
                case 'update_order_pos':
                    $order_pos = Yii::app()->request->getPost('order_pos');
                    if (!empty($order_pos)) {
                        foreach ($order_pos as $key => $value) {
                            Feedback::model()->updateByPk($key, array('order_pos' => $value));
                        }
                    }
                    break;
                case 'delete_selected':
                    $select = Yii::app()->request->getPost('select');
                    if (!empty($select)) {
                        foreach ($select as $id) {
                            $model = Feedback::model()->findByPk($id)->delete();
                        }
                    }
                    break;
                case 'move_to_recycle_bin':
                    $select = Yii::app()->request->getPost('select');
                    if (!empty($select)) {
                        foreach ($select as $id) {
                            $model = Feedback::model()->updateByPk($id, array(
                                'status' => Options::STATUS_PENDING_DELETE));
                        }
                    }
                    break;
            }

            $this->redirect(array('index', 'node' => Yii::app()->request->getPost('current_node')));
        } else {
            throw new CHttpException(400, Yii::t('common', 'invalid_request'));
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $current_node = Yii::app()->request->getParam('node');
        $criteria = new CDbCriteria;
        $criteria->condition = 'status != ' . Options::STATUS_PENDING_DELETE;
        if (intval($current_node)) {
            $criteria->addCondition("node_id = {$current_node}");
        }
        $type = Yii::app()->request->getParam('type', 'all');
        switch (trim($type)) {
            case 'replied':
                $criteria->addCondition('is_replied = ' . Feedback::REPLIED_YES);
                break;
            case 'unreplied':
                $criteria->addCondition('is_replied = ' . Feedback::REPLIED_NO);
                break;
        }

        $pages = new CPagination(Feedback::model()->count($criteria));
        $pages->pageSize = self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $sort = new CSort('Feedback');
        $sort->applyOrder($criteria);

        $models = Feedback::model()->findAll($criteria);

        $this->render('index', array(
            'models' => $models,
            'pages' => $pages,
            'sort' => $sort,
            'current_node' => $current_node,
        ));
    }

    // change status
    public function actionChangeStatus() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = Feedback::model()->findByPk($id);
            switch ($model->status) {
                case Options::STATUS_DRAFT:
                    $status = Options::STATUS_PUBLISHED;
                    break;
                case Options::STATUS_PUBLISHED:
                    $status = Options::STATUS_DRAFT;
                    break;
            }
            $model->status = $status;
            try {
                $model->save(false);
            } catch (Exception $ex) {
                echo $ex;
            }

            echo $model->statusIconFormat;
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadFeedback($id=null) {
        if($this->_model===null) {
            if($id!==null || isset($_GET['id']))
                $this->_model=Feedback::model()->findbyPk($id!==null ? $id : $_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Executes any command triggered on the admin page.
     */
    protected function processAdminCommand() {
        if(isset($_POST['command'], $_POST['id']) && $_POST['command']==='delete') {
            $this->loadFeedback($_POST['id'])->delete();
            // reload the current page to avoid duplicated delete actions
            $this->refresh();
        }
    }
}
